<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        #can {
            display: block;
        }
    </style>
</head>

<body>
    <canvas id="can"></canvas>
    <script>
        const oCan = document.getElementById('can')
        // 将视口宽高设为画布宽高
        oCan.width = document.documentElement.clientWidth
        oCan.height = document.documentElement.clientHeight
        // 获取画布上下文对象
        const ctx = oCan.getContext('2d')
        ctx.lineCap = 'round'
        // 设置线条描边颜色
        ctx.strokeStyle = 'pink'
        // 设置线条宽度
        ctx.lineWidth = 5
        // 默认不绘制
        let flag = false
        // 初始化上一个点的坐标变量
        let last
        // 判断是否是触摸设备
        const isTouch = 'ontouchstart' in document.documentElement
        if (isTouch) {
            // 手指触摸屏幕时触发事件
            oCan.ontouchstart = e => {
                // 获取触摸点坐标
                let x = e.touches[0].clientX
                let y = e.touches[0].clientY
                last = [x, y]
            }
            // 手指在屏幕上移动时触发事件
            oCan.ontouchmove = e => {
                let x = e.touches[0].clientX
                let y = e.touches[0].clientY
                // 绘制线条
                draw(last[0], last[1], x, y)
                last = [x, y]
            }
        }
        else {
            oCan.onmousedown = e => {
                flag = true
                last = [e.clientX, e.clientY]
            }
            oCan.onmousemove = e => {
                if (flag === true) {
                    draw(last[0], last[1], e.clientX, e.clientY)
                    last = [e.clientX, e.clientY]

                }
            }
            oCan.onmouseup = e => {
                flag = false
            }
        }
        // 定义一个绘制线条的函数
        function draw(x1, y1, x2, y2) {
            ctx.beginPath()
            ctx.moveTo(x1, y1)
            ctx.lineTo(x2, y2)
            ctx.stroke()
        }
    </script>
</body>

</html>